package com.atguigu.controller;

import com.atguigu.domain.Permission;
import com.atguigu.domain.Role;
import com.atguigu.domain.UserInfo;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
@Secured("ROLE_USER")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("findAll.do")
    public ModelAndView findAll(){
        ModelAndView mv = new ModelAndView();
        List<Role> roles = roleService.findAll();
        mv.addObject("roleList",roles);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("save.do")
    public String findAll(Role role){
        roleService.save(role);
        return "redirect:findAll.do";
    }

    //查询指定id的用户
    @RequestMapping("findById.do")
    public ModelAndView findById(String id){
        ModelAndView mv = new ModelAndView();
        Role role = roleService.findById(id);
        mv.addObject("role",role);
        mv.setViewName("role-show");
        return mv;
    }
    //删除角色
    @RequestMapping("deleteRole.do")
    public String deleteRole(@RequestParam(name = "id",required = true) String roleId){
        System.out.println(roleId);
        roleService.deleteRole(roleId);
        return "redirect:findAll.do";
    }

    //查询角色以及角色可以添加的权限
    @RequestMapping("findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id",required = true) String id){
        ModelAndView mv = new ModelAndView();
        //1.根据id查询角色
        Role role= roleService.findById(id);
        //2.根据用户id查询可以添加的权限
        List<Permission> otherPermission = roleService.findOtherPermission(id);
        mv.addObject("permissionList",otherPermission);
        mv.addObject("role",role);
        mv.setViewName("role-permission-add");
        return mv;
    }

    @RequestMapping("addPermissionToRole.do")
    public String addPermissionToRole(@RequestParam(name = "roleId",required = true) String roleId,
                                @RequestParam(name = "ids",required = true) String[] permissionIds){
        roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll.do";
    }


}
